import {
  ADD_TAB,
  DEL_TAB,
  INIT_TAB,
  SET_CURRENT_TAB,
  SET_TAB_LIST,
  DEL_LEFT_TABS,
  DEL_RIGHT_TABS,
  DEL_OTHER_TABS,
} from "./actionTypes";
// import store from "@/store";
import i18n from "@/locale";

// console.log("store in logger", store);

function setCurrentTab(state, propTab) {
  state.currentTab = propTab;
}

export default {
  [ADD_TAB](state, addTab) {
    const tabIsExist = state.tabList.some(
      (item) => item.name === addTab.name || item.path === addTab.path
    );
    if (!tabIsExist) {
      state.tabList.push(addTab);
    } else {
      //
    }
    setCurrentTab(state, addTab);
  },
  [DEL_TAB](state, delTab) {
    const tabIsExist = state.tabList.some(
      (item) => item.name === delTab.name || item.path === delTab.path
    );
    if (tabIsExist) {
      const tabIdx = state.tabList.findIndex(
        (item) => item.name === delTab.name || item.path === delTab.path
      );
      // delTab.name == currentTab.name -> currentTab -> last-index-tab
      if (delTab.name == state.currentTab.name) {
        /*
          1. 找到当前的索引
          2. 回退上一个tab
            - 如果有上一个tab, currentTab -> lastIdxTab
            - 如果没有上一个, currentTab就切换到下一个tab中
        */
        const delTabIdx = state.tabList.findIndex(
          (item) => item.name === delTab.name
        );
        if (delTabIdx) {
          const lastIdxTab = state.tabList[delTabIdx - 1];
          setCurrentTab(state, lastIdxTab);
        }
      }
      // handle-remove-tab
      state.tabList.splice(tabIdx, 1);
    }
  },
  [INIT_TAB](state) {
    const indexTab = {
      name: "Introdution",
      path: "/index-page",
      fullPath: "/index-page",
      meta: {
        title: i18n.t("ROUTES.Introdution"),
      },
    };

    setCurrentTab(state, indexTab);

    state.tabList = [{ ...indexTab }];
  },
  [SET_CURRENT_TAB](state, currentTab) {
    state.currentTab = currentTab;
  },
  [SET_TAB_LIST](state, tabList) {
    state.tabList = tabList;
  },
  [DEL_LEFT_TABS]() {},
  [DEL_RIGHT_TABS]() {},
  [DEL_OTHER_TABS]() {},
};
